package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.RecruitmenPlan;
import cn.wolfcode.crm.domain.RecruitmenPlanBill;
import cn.wolfcode.crm.mapper.RecruitmenPlanBillMapper;
import cn.wolfcode.crm.mapper.RecruitmenPlanMapper;
import cn.wolfcode.crm.query.QueryForObject;
import cn.wolfcode.crm.service.IRecruitmenPlanService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class RecruitmenPlanImpl implements IRecruitmenPlanService {

    @Autowired
    private RecruitmenPlanMapper recruitmenPlanMapper;
    @Autowired
    private RecruitmenPlanBillMapper recruitmenPlanBillMapper;

    public void deleteByPrimaryKey(Long id) {
        //删除明细
        recruitmenPlanBillMapper.deleteByPlanId(id);

        recruitmenPlanMapper.deleteByPrimaryKey(id);
    }

    public void insert(RecruitmenPlan recruitmenPlan) {
        //获得当前对象
        Employee currentUser = (Employee) SecurityUtils.getSubject().getPrincipal();
        recruitmenPlan.setPlanPerson(currentUser);
       //获得当前时间
        recruitmenPlan.setPlanTime(new Date());
        //保存
        recruitmenPlanMapper.insert(recruitmenPlan);

        //保存明细信息
        saveBill(recruitmenPlan);
    }

    public RecruitmenPlan selectByPrimaryKey(Long id) {
        return recruitmenPlanMapper.selectByPrimaryKey(id);
    }

    public List<RecruitmenPlan> selectAll() {
        return recruitmenPlanMapper.selectAll();
    }

    public void updateByPrimaryKey(RecruitmenPlan recruitmenPlan) {
        //删除明细
        recruitmenPlanBillMapper.deleteByPlanId(recruitmenPlan.getId());
        //判断状态
        if (recruitmenPlan.getState()==2){
            //设置审核人
            //获得当前对象
            Employee currentUser = (Employee) SecurityUtils.getSubject().getPrincipal();
            recruitmenPlan.setAuditPerson(currentUser);
            //设置审核时间
            recruitmenPlan.setAuditTime(new Date());
        }
        //保存明细信息
        saveBill(recruitmenPlan);

        recruitmenPlanMapper.updateByPrimaryKey(recruitmenPlan);
    }

    public PageResult queryListByQo(QueryForObject qo) {
        int total = recruitmenPlanMapper.getTotalByQo(qo);
        if (total == 0) {
            return new PageResult();
        }
        List<RecruitmenPlan> rows = recruitmenPlanMapper.getListByQo(qo);
        return new PageResult(total, rows);
    }

    //保存明细信息
    private void saveBill(RecruitmenPlan recruitmenPlan){
        if (recruitmenPlan.getBills() != null) {
            List<RecruitmenPlanBill> bills = recruitmenPlan.getBills();
            for (RecruitmenPlanBill bill : bills) {
                bill.setRecruitmentPlanId(recruitmenPlan.getId());
                recruitmenPlanBillMapper.insert(bill);
            }
        }
    }
}
